<template>
  <div class="login">
    <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="120px" class="loginForm">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username" type="username" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login(ruleFormRef)">确定</el-button>
        <el-button>重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router';
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { getuserlogin } from '../request/api'
import { useStore } from 'vuex';
let store = useStore()
//绑定表单节点
const ruleFormRef = ref<FormInstance>()
let router = useRouter()
//定义数据
let ruleForm = reactive({
  username: '',
  password: ''
})
//表单验证
let rules = reactive<FormRules>({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 8, message: "长度2-8之间", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 16, message: "长度6-16之间", trigger: "blur" },
  ],
});

//封装一个登录事件
let login = (formEl: FormInstance | undefined) => {
  if (formEl) {
    formEl.validate((val) => {
      if (val) {
        getuserlogin(ruleForm).then((res: any) => {
          if (res.code == 200) {
            ElMessage.success(res.msg)
            //把信息存储到本地
            sessionStorage.setItem('userinfo', JSON.stringify(res.list))
            //调用vuex函数把信息传给派遣的触发函数
            store.dispatch('getUserAction',res.list)
            //跳转到index界面
            router.push('/index')
          } else {
            ElMessage.error(res.msg)
          }
        })


      }
    })
  } else {

  }
};

</script>

<style lang="less" scoped>
.login {
  width: 100vw;
  height: 100vh;

  .loginForm {
    position: absolute;
    width: 400px;
    height: 350px;
    top: 50%;
    left: 50%;
    margin: -175px 0 0 -150px;
  }
}
</style>